package edu.stanford.cs.cs294s;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class ServerConnection {
	private String mServerUrl;
	
	public ServerConnection(String serverUrl){
		mServerUrl = serverUrl;
	}
	
	public boolean addFact(int index, String newFact){
		String res = sendUpdateDataRequest(Integer.toString(index), newFact);
		if(res.contains("Success"))
			return true;
		else
			return false;
	}
	
	public List<Point> getAllPoints(){
		String points = sendRequest();
		System.err.println("JSON String:\n" + points);
		Object obj = JSONValue.parse(points);
	    JSONObject retValTop = (JSONObject) obj;
	    System.err.println("JSON : \n" + retValTop.toJSONString());
	    JSONArray retValArr = (JSONArray)retValTop.get("sample");
	
    	List<Point> pointObjs = new ArrayList<Point>();
	    //For now just one point
	    for(int i=0; i<retValArr.size(); i++){
	    	JSONObject retVal = (JSONObject)retValArr.get(i);
	    	Point pointObj = new Point();
	    	pointObj.setName((String)retVal.get("name"));
//	    	String lat = (String)retVal.get("latitude");
//	    	String lon = (String)retVal.get("longitude");
//	    	System.err.println("Latitude/Longitude " + lat + "," + lon);
	    	pointObj.setFacts((String)retVal.get("facts"));
	    	double lat = Double.parseDouble((String)retVal.get("latitude"));
	    	double lon = Double.parseDouble((String)retVal.get("longitude"));
	    	lat *= 1E6;
	    	lon *= 1E6;
	    	int index = Integer.parseInt((String)retVal.get("placeindex"));
	    	pointObj.setIndex(index);
	    	pointObj.setLatitude((int)lat);
	    	pointObj.setLongitude((int)lon);
	    	pointObjs.add(pointObj);
	    }
	    return pointObjs;
	}

	public String sendRequest(){
		String line = "";
		try
		{
			URL url = new URL(mServerUrl);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			
		    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
//			wr.write(data);
		    wr.flush();
		    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		    line = rd.readLine();
		    wr.close();
		    rd.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return line;
	}
	
	public String sendUpdateDataRequest(String index, String newfact){
		String line = "";
		
		try
		{
			String updateUrl = mServerUrl + "?placeindex=" + index + "&newfact=" + newfact;
			updateUrl = updateUrl.replaceAll(" ", "%20");
			System.err.println("UPDATEURL  " + updateUrl);
			URL url = new URL(updateUrl);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
		
			//String data = URLEncoder.encode("placeindex", "UTF-8") + "=" + URLEncoder.encode(index, "UTF-8");
		    //data += "&" + URLEncoder.encode("newfact", "UTF-8") + "=" + URLEncoder.encode(newfact, "UTF-8");
		    
		    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
			//wr.write(data);
		    wr.flush();
		    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		    line = rd.readLine();
		    wr.close();
		    rd.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return line;
	}
	
}
